<script setup lang="ts">
import {useStore} from "@/stores";
import {onUnmounted, reactive, ref, useTemplateRef} from "vue";

import {useRouter} from "vue-router";

import {ElMessage} from "element-plus";
import type {FormInstance} from "element-plus";

import {StatusCode} from "@/api";

const store = useStore();
const router = useRouter();

const logging = ref(false);
const form = reactive({username: '', password: ''});
const loginForm = useTemplateRef<FormInstance>("loginForm");

const login = () => {
  loginForm.value?.validate((isValid) => {
    if(isValid) {
      logging.value = true;

      store.user.login(form.username, form.password).then((resp) => {
        if(resp.data.code === StatusCode.LOGIN_SUCCESS) {
          router.push('/home');
          ElMessage.success('登录成功');
        } else {
          ElMessage.error(resp.data.data);
        }
      }).finally(() => logging.value = false);
    }
  });
};

const loginOnEnter = (e: KeyboardEvent) => {
  if (e.key === "Enter") {
    login();
  }
};

window.addEventListener("keydown", loginOnEnter);
onUnmounted(() => {
  window.removeEventListener("keydown", loginOnEnter);
})

</script>

<template>
  <el-card style="position: relative; top: 50vh; transform: translateY(-50%); width: 40%; min-width: 750px; padding: 20px; margin: 0 auto">
    <el-form ref="loginForm" label-position="top" status-icon :model="form" hide-required-asterisk :disabled="logging" style="padding: 100px">
      <el-form-item :rules="[{required: true, message: '请输入用户名'}]" label="用户名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item :rules="[{required: true, message: '请输入密码'}]" label="密码" prop="password">
        <el-input type="password" v-model="form.password" />
      </el-form-item>
      <el-button type="primary" style="width: 100%; margin-top: 30px" :loading="logging" @click="login">登录</el-button>
    </el-form>
  </el-card>
</template>

<style scoped>

</style>